# -*- coding: UTF-8 -*-
# Create your views here.
#import Image
from django.db.models.query import QuerySet
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render, render_to_response, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from django.core.urlresolvers import reverse
from django.db.models import Count

from eeacl.casestudy.models import *

from django.contrib.auth.decorators import login_required

from django.core.mail import send_mail, EmailMultiAlternatives

import random
import string
import eeacl.settings
from django.views.decorators.csrf import csrf_exempt
from PIL import Image as PILImage
import os
import uuid
import datetime

from pgmagick import Image, FilterTypes
from pgmagick import Image, FilterTypes

from django.utils import simplejson


def index(request):
    flashs = FlashInfo.objects.all().order_by('sort')[:5]
    categorys = Category.objects.all().order_by('priority')
    category_dict = {}
    for category in categorys:
        cases = Case.objects.filter(category=category).order_by('date')[:1]
        category_dict[category] = cases
    latest_cases = Case.objects.order_by('-date')[:11]
    hotest_cases = Case.objects.order_by('-count')[:11]
    return render(request, 'index.html',
                  {'category_cases': category_dict, 'flashs': flashs, 'latest_cases': latest_cases,
                   'hotest_cases': hotest_cases})


def category(request):
    categorys = Category.objects.all().order_by('priority')
    category_dict = {}
    for category in categorys:
        cases = Case.objects.filter(category=category).order_by('date')[:6]
        category_dict[category] = cases
    latest_cases = Case.objects.order_by('date')[:11]
    hotest_cases = Case.objects.order_by('-count')[:11]
    return render(request, 'category.html',
                  {'category_cases': category_dict, 'latest_cases': latest_cases, 'hotest_cases': hotest_cases})


def contact(request):
    return render(request, 'contact.html', {})


def list(request):
    category = request.GET['category']
    type = request.GET['type']
    offset = request.GET['no']
    if offset:
        if category:
            cases = Case.objects.filter(category=Category.objects.get(pk=category)).order_by('-id')[
                    int(offset):int(offset) + 9]
        if type == 'latest':
            cases = Case.objects.all().order_by('-id')[int(offset):int(offset) + 9]
        if type == 'rank':
            cases = Case.objects.all().order_by('-count')[int(offset):int(offset) + 9]
        return render(request, 'cell.html', {'case': cases})
    return render(request, 'list.html', {'category': category, 'type': type})


@login_required(login_url='/login/')
def personal(request):
    user = User.objects.get(username=request.user)
    if user:
        totalCount = BrowseHistory.objects.filter(user=user).count()
        import math

        if 0 == totalCount:
            pageCount = 0
        else:
            pageCount = int(math.ceil(float(totalCount) / 10))
    return render(request, 'personal.html', {'totalCount': totalCount, 'pageCount': pageCount})


def personalPage(request):
    user = User.objects.get(username=request.user)
    pagenumber = request.GET['pagenumber']
    if user and pagenumber:
        offset = 10
        startnum = (int(pagenumber) - 1) * offset
        endnum = int(pagenumber) * offset
        list = BrowseHistory.objects.filter(user=user).order_by('id')[startnum:endnum]
        if list:
            return render(request, 'personalPage.html', {'list': list, 'page': int(pagenumber)})
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")


@login_required(login_url='/login/')
def personalcase(request):
    user = User.objects.get(username=request.user)
    if user:
        totalCount = Case.objects.filter(user=user).count()
        import math

        if 0 == totalCount:
            pageCount = 0
        else:
            pageCount = int(math.ceil(float(totalCount) / 10))
    return render(request, 'personalcase.html', {'totalCount': totalCount, 'pageCount': pageCount})


def personalcasePage(request):
    user = User.objects.get(username=request.user)
    pagenumber = request.GET['pagenumber']
    if user and pagenumber:
        offset = 10
        startnum = (int(pagenumber) - 1) * offset
        endnum = int(pagenumber) * offset
        list = Case.objects.filter(user=user).order_by('id')[startnum:endnum]
        if list:
            return render(request, 'personalcasePage.html', {'list': list, 'page': int(pagenumber)})
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")


@login_required(login_url='/login/')
def personalfavorite(request):
    user = User.objects.get(username=request.user)
    if user:
        totalCount = Favorite.objects.filter(user=user).count()
        import math

        if 0 == totalCount:
            pageCount = 0
        else:
            pageCount = int(math.ceil(float(totalCount) / 10))
    return render(request, 'personalfavorite.html', {'totalCount': totalCount, 'pageCount': pageCount})


def personalfavoritePage(request):
    user = User.objects.get(username=request.user)
    pagenumber = request.GET['pagenumber']
    if user and pagenumber:
        offset = 10
        startnum = (int(pagenumber) - 1) * offset
        endnum = int(pagenumber) * offset
        list = Favorite.objects.filter(user=user).order_by('id')[startnum:endnum]
        if list:
            return render(request, 'personalfavoritePage.html', {'list': list, 'page': int(pagenumber)})
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")


def signup(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        userProfileForm = UserProfileForm(request.POST)
        if form.is_valid():
            users = User.objects.filter(email=request.POST['email'])
            if not users:
                user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'],
                                                form.cleaned_data['password'])
                user.save()
                user_profile = UserProfile(user=user)
                user_profile.avatar = "/photos/avatar.gif"
                user_profile.company = request.POST['company']
                user_profile.industry = request.POST['industry']
                user_profile.scale = request.POST['scale']
                user_profile.position = request.POST['position']
                user_profile.save()
                user = authenticate(username=request.POST['username'], password=request.POST['password'])
                login(request, user)
                try:
                    send_mail(_('Register eeacl account successful!'),
                              _('You had registered djangosns account successfully!'),
                              'eeacl@eeacl.com', [form.cleaned_data['email']], fail_silently=False)
                except:
                    pass
            else:
                return render(request, 'signup.html', {'form': form, 'userProfileForm': userProfileForm,
                                                       'error': _('Email has been registered!')})
            return HttpResponseRedirect('/')
        return render(request, 'signup.html', {'form': form, 'userProfileForm': userProfileForm})
    if request.method == 'GET':
        form = UserForm()
        userProfileForm = UserProfileForm()
        return render(request, 'signup.html', {'form': form, 'userProfileForm': userProfileForm})


def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            if user.is_active:
                login(request, user)
                if request.POST['next'] != '0':
                    return HttpResponseRedirect(request.POST['next'])
                else:
                    return redirect('/')
        else:
            return render(request, "login.html", {'form': form, 'error': _('Username or password is invalid!')})
    else:
        form = LoginForm()
        next = '0'
        if request.GET.has_key('next'):
            next = request.GET['next']
        return render(request, "login.html", {'form': form, 'next': next})


@login_required(login_url='/login/')
def case_add(request):
    if request.method == 'POST':
        if request.LANGUAGE_CODE == 'zh-cn':
            form = CaseForm(request.POST)
        else:
            form = CaseForm_En(request.POST)
    else:
        if request.LANGUAGE_CODE == 'zh-cn':
            form = CaseForm()
        else:
            form = CaseForm_En()
            #form.company_scale = CompanyScale.objects.get()
    return render(request, "addcase.html", {'form': form})


@login_required(login_url='/login/')
def case_update_index(request, caseId):
    if request.method == 'GET':
        if caseId:
            case = Case.objects.get(pk=caseId)
            if request.LANGUAGE_CODE == 'zh-cn':
                form = CaseForm(data={'name': case.name, 'author': case.author, 'company': case.company,
                                      'company_scale': case.company_scale, 'category': case.category,
                                      'employee_scale': case.employee_scale, 'country': case.country,
                                      'province': case.province, 'city': case.city, 'ownership': case.ownership,
                                      'industry': case.industry, 'department': case.department, 'brief': case.brief,
                                      'description': case.description, 'keywords': case.keywords})
            else:
                form = CaseForm_En(data={'name': case.name, 'author': case.author, 'company': case.company,
                                         'company_scale': case.company_scale, 'category': case.category,
                                         'employee_scale': case.employee_scale, 'country': case.country,
                                         'province': case.province, 'city': case.city, 'ownership': case.ownership,
                                         'industry': case.industry, 'department': case.department, 'brief': case.brief,
                                         'description': case.description, 'keywords': case.keywords})
            return render(request, 'addcase.html', {'form': form, 'caseId': caseId})
    else:
        case_add(request)


def case_update(request):
    if request.method == 'POST':
        caseId = request.POST['caseId']
        form = CaseForm(request.POST)
        if form.is_valid() and caseId:
            try:
                case = Case.objects.get(pk=caseId)
            except:
                raise Http404
            if case:
                data = form.cleaned_data
                case.name = data['name']
                case.author = data['author']
                case.company = data['company']
                case.category = data['category']
                case.company_scale = data['company_scale']
                case.employee_scale = data['employee_scale']
                case.country = data['country']
                case.province = data['province']
                case.city = data['city']
                case.ownership = data['ownership']
                case.industry = data['industry']
                case.department = data['department']
                case.brief = data['brief']
                case.keywords = data['keywords']
                case.description = data['description']
                if data['img']:
                    case.img = data['img']
                case.save()
                if data['img']:
                    resizeImg(str(case.img.path))
                return HttpResponseRedirect('/my/case/')
        else:
            return render(request, 'addcase.html', {'form': form, 'caseId': caseId})


@login_required(login_url='/login/')
def save_case(request):
    if request.method == 'POST':
        form = CaseForm(request.POST, request.FILES)
        if form.is_valid():
            # company_scale = CompanyScale.objects.get(pk=)
            #employee_scale = EmployeeScale.objects.get(pk=)
            #ownership = Ownership.objects.get(pk=)
            #industry = Industry.objects.get(pk=)
            #department = Department.objects.get(pk=form.cleaned_data['department'])
            case = Case(name=form.cleaned_data['name'], author=form.cleaned_data['author'],
                        company=form.cleaned_data['company'], category=form.cleaned_data['category'],
                        company_scale=form.cleaned_data['company_scale'], count=0,
                        employee_scale=form.cleaned_data['employee_scale'], country=form.cleaned_data['country'],
                        province=form.cleaned_data['province'], city=form.cleaned_data['city'],
                        ownership=form.cleaned_data['ownership'], industry=form.cleaned_data['industry'],
                        department=form.cleaned_data['department'], brief=form.cleaned_data['brief'],
                        description=form.cleaned_data['description'], img=form.cleaned_data['img'],
                        keywords=form.cleaned_data['keywords'], user=request.user)
            case.save()
            if case.img:
                path = case.img.path
                resizeImg(str(path))
            return render(request, 'addMoreInfo.html', {'caseId': case.id, 'caseName': case.name})
        else:
            return case_add(request)
    else:
        return case_add(request)


def resizeImg(img):
    if img:
        img = os.path.join(eeacl.settings.FILE_UPLOAD_TEMP_DIR, img)
        imgMiddle = Image(img)
        imgMiddle.scale('280x210')
        imgMiddle.write(img + '-280x210')
        imgBig = Image(img)
        imgBig.scale('640x480')
        imgBig.write(img + '-640x480')


@login_required(login_url='/login/')
def casedetail(request, id):
    if request.method == 'GET':
        if id:
            case = Case.objects.get(pk=id)
            if case:
                user = User.objects.get(username=request.user)
                answer = Answer.objects.filter(case=case).values('user_id').distinct()
                s = []
                for au in answer:
                    s.append(User.objects.get(pk=au['user_id']))
                    #判断用户是否已经答过题
                answer_user = Answer.objects.filter(user=user, case=case).order_by('question')
                #問題列表
                question = Question.objects.all().order_by('sort')
                sa = []
                for q in question:
                    isanswer = False
                    for a in answer_user:
                        if a.question.id == q.id:
                            sa.append(a)
                            isanswer = True
                            continue
                    if isanswer:
                        pass
                    else:
                        newa = Answer(question=q, content='')
                        sa.append(newa)
                        #problems = Problem.objects.filter(case=case).order_by('-date')
                keywords = case.keywords.split(',')
                if keywords and case.keywords:
                    pass
                else:
                    keywords = None
                favorite = Favorite.objects.filter(user=user, case=case)
                browse = BrowseHistory.objects.filter(case=case, user=user)
                video = Video.objects.filter(case=case).order_by('id')
                if browse:
                    pass
                else:
                    browseHistory = BrowseHistory(case=case, user=user)
                    browseHistory.save()
                    case.count += 1
                    case.save()
            return render(request, "casedetail.html",
                          {'case': case, 'keywords': keywords, 'favorite': favorite,
                           'video': video, 'answer': answer, 'answer_user': answer_user, 'question': question,
                           'question_size': question.count(), 'sa': sa, 's': s})


@login_required(login_url='/login/')
def caseAttach(request):
    if request.method == "GET":
        caseId = request.GET['caseId']
        return render(request, 'addVideo.html', {'pictures': None, 'caseId': caseId})
    raise Http404


@login_required(login_url='/login/')
def editAttach(request):
    if request.method == "GET":
        caseId = request.GET['caseId']
        case = Case.objects.get(pk=caseId)
        if case:
            if request.user == case.user:
                video = Video.objects.filter(case=case).order_by('id')
                return render(request, 'editVideo.html', {'video': video, 'caseId': caseId})
    raise Http404


@login_required(login_url='/login/')
def delAttach(request, videoId):
    if request.method == "GET":
        video = Video.objects.get(pk=videoId)
        if video:
            if request.user == video.case.user:
                path = video.link
                filename = path.split('/')[2]
                pathdirect = path.split('/')[1]
                ##targerfile = os.path.join(eeacl.settings.FILE_UPLOAD_TEMP_DIR, pathdirect + "\\" + filename)
                targerfile = os.path.join(eeacl.settings.FILE_UPLOAD_TEMP_DIR, pathdirect + "/" + filename)
                if os.path.isfile(targerfile):
                    os.remove(targerfile)
                    video.delete()
                    return render(request, 'editVideo.html',
                                  {'video': Video.objects.filter(case=video.case), 'caseId': video.case.id})
    raise Http404


def search(request):
    if request.method == 'POST':
        return render(request, "search.html", {"query": request.POST['q']})
    else:
        return render(request, "search.html", {})


def casequeryIndex(request):
    ownership = Ownership.objects.all()
    industry = Industry.objects.all()
    companyScale = CompanyScale.objects.all()
    problemtype = ProblemType.objects.all()
    department = Department.objects.all()
    return render(request, "casequery.html",
                  {'ownership': ownership, 'industry': industry, 'companyScale': companyScale,
                   'problemtype': problemtype, 'department': department})


def casequery(request):
    offset = request.GET['no']
    ownership = request.GET['ownership']
    companyscacle = request.GET['companyscacle']
    industry = request.GET['industry']
    department = request.GET['department']
    problemtype = request.GET['problemtype']
    caseId = request.GET['caseId']
    author = request.GET['author']
    case = Case.objects.all()
    if caseId.strip():
        case = case.filter(id=caseId)
    if author.strip():
        case = case.filter(author=author)
    if ownership:
        case = case.filter(ownership=Ownership.objects.get(pk=ownership))
    if companyscacle:
        case = case.filter(company_scale=CompanyScale.objects.get(pk=companyscacle))
    if industry:
        case = case.filter(industry=Industry.objects.get(pk=industry))
    if department:
        case = case.filter(department=Department.objects.get(pk=department))
    if problemtype:
        problem = Problem.objects.filter(problem_type=ProblemType.objects.get(pk=problemtype))
        if problem:
            case = case.filter(id__in=problem.values('case_id'))
        else:
            case = None
    if case:
        case = case.order_by('-id')[int(offset):int(offset) + 9]
    else:
        case = None
    return render(request, 'cell.html', {'case': case})


@login_required(login_url='/login/')
def saveComment(request):
    caseid = request.GET['caseId']
    content = request.GET['content']
    case = Case.objects.get(pk=caseid)
    if case:
        try:
            comment = Comment(case=case, content=content, user=request.user)
            comment.save()
            return HttpResponse("1")
        except Exception, ex:
            print ex.message
            return HttpResponse(_("System error, please try again later!"))
    else:
        return HttpResponse(_("System error, please try again later!"))


def queryCommentPage(request):
    caseId = request.GET['caseId']
    pagenumber = request.GET['pagenumber']
    if caseId and pagenumber:
        offset = 4
        startnum = (int(pagenumber) - 1) * offset
        endnum = int(pagenumber) * offset
        list = Comment.objects.filter(case_id=caseId)[startnum:endnum]
        if list:
            return render(request, 'commentPage.html', {'list': list, 'page': int(pagenumber)})
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")


@login_required(login_url='/login/')
def addfavorite(request):
    if request.method == 'GET':
        caseId = request.GET['caseId']
        if caseId:
            case = Case.objects.get(pk=caseId)
            if case:
                favorite = Favorite(case=case, user=request.user)
                favorite.save()
                return HttpResponse(_("Success"))
    return HttpResponse(_("Fail"))


def logout_view(request):
    logout(request)
    return HttpResponseRedirect('/')


def forget_password(request):
    if request.method == 'POST':
        email = request.POST['email']
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            user = None
        if user:
            #生成一个字符串,长度为10到20
            activation_key = random_string(random.randint(10, 20));
            #将用户名,字符串,当前时间存入数据库
            #检测是否存在
            findPasses = UserProfile.objects.filter(user=user)
            if findPasses: #已经存在
                findPass = findPasses[0]
                findPass.activation_key = activation_key #更新key
            else:
                findPass = UserProfile(user=user, activation_key=activation_key)
            findPass.save()
            #发送email
            #th = Thread(target=send_mail,
            #    args=('Reset password!Not reply! ',
            #        'click the url http://djangosns/account/resetpassowrd/'+activation_key,
            #        [email]))
            #th.start()
            subject, from_email, to = _('Eeacl reset password'), 'suyu8776@163.com', email,
            text_content = _('This is an reset password email.')
            html_content = _(
                'click') + ' <a href="' + eeacl.settings.DOMAIN + '/my/password/reset/' + activation_key + '/">' + eeacl.settings.DOMAIN + '/my/password/reset/' + activation_key + '/</a> ' + _(
                'to reset password')
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            #跳转页面
            return render_to_response('emailDes.html')
        else:
            #用户不存在的操作
            form = ResetPassForm()
            return render(request, 'forget_password.html', {'form': form, 'error': 'Email is not exists!'})
    else:
        form = ResetPassForm()
        return render(request, "forget_password.html", {'form': form})


def begin_reset_password(request, activation_key):
    findPasses = UserProfile.objects.filter(activation_key=activation_key)
    if findPasses:
        findPass = findPasses[0]
        #将User存入session或其他...
        user = findPass.user
        request.session['findpasser'] = user
        #定向到重置密码解密
        return render(request, 'reset_password.html', {'user': user})
    return render_to_response('404.html')


def reset_password(request):
    password = request.POST['password']
    user = request.session['findpasser']
    if user:
        user.set_password(password)
        user.save()
        #修改成功后的操作
        #更新记录
        userProfile = UserProfile.objects.get(user=user)
        userProfile.activation_key = ''
        userProfile.save()
        #删除session
        del request.session['findpasser']
        return HttpResponseRedirect('/login/')
    else:
        return render_to_response('404.html')


@login_required(login_url='/login/')
def changePassword(request):
    if request.method == 'POST':
        password = request.POST['password']
        u = User.objects.get(username=request.user)
        user = authenticate(username=request.user.username, password=request.POST['originalPassword'])
        if user:
            u.set_password(password)
            u.save()
            return render(request, 'changePassword.html', {"message": _('Password modify successfully!')})
        else:
            return render(request, 'changePassword.html', {"message": _('Password can not match current user!')})
    else:
        return render(request, 'changePassword.html', {})


def random_string(num):
    passward = ''
    seed = string.letters + string.digits
    for i in xrange(num):
        passward += seed[random.randrange(1, len(seed))]
    return passward


def getProvinceSelectList(request):
    provs = []
    countryid = request.GET['id']
    lang = request.GET['lang']
    if countryid and lang:
        country = Country.objects.get(pk=countryid)
        proviceList = Province.objects.filter(country=country)
        if proviceList is not None:
            for prov in proviceList:
                p = {}
                p['label'] = prov.id
                if lang == 'en':
                    p['text'] = prov.name
                if lang == 'zh-cn':
                    p['text'] = prov.name_cn
                provs.append(p)
            return HttpResponse(simplejson.dumps(provs))


def getCitySelectList(request):
    citys = []
    provid = request.GET['id']
    lang = request.GET['lang']
    if provid and lang:
        prov = Province.objects.get(pk=provid)
        cityList = City.objects.filter(province=prov)
        if cityList is not None:
            for city in cityList:
                c = {}
                c['label'] = city.id
                if lang == 'en':
                    c['text'] = city.name
                if lang == 'zh-cn':
                    c['text'] = city.name_cn
                citys.append(c)
            return HttpResponse(simplejson.dumps(citys))


@csrf_exempt
def uploadify_script(request):
    if request.method == 'POST':
        CKEditorFuncNum = request.GET['CKEditorFuncNum']
        response = HttpResponse()
        response['Content-Type'] = "text/html; charset=UTF-8"
        file = request.FILES.get("upload", None)
        if file:
            fileName = profile_upload(file)
            res = '<script type="text/javascript">'
            res += 'window.parent.CKEDITOR.tools.callFunction(%s,"%s","%s");' % (
                CKEditorFuncNum, '/file/upload/' + fileName, '')
            res += '</script>'
            response.write(res)
        return response


@csrf_exempt
def fileupload(request):
    if request.method == 'POST':
        file = request.FILES.get("upload", None)
        caseId = request.POST['caseId']
        filename = request.POST['filename']
        filesize = request.POST['filesize']
        f = {}
        try:
            if file and caseId and filename and filesize:
                fileType = file.name.split('.')[-1]
                if fileType:
                    typelist = ['MP4', 'FLV', 'PDF', 'DOC', 'DOCX', 'XLS']
                    if typelist.count(fileType.upper()) > 0:
                        if fileType.upper() == "PDF":
                            img = "/assets/images/pic/pdf.jpg"
                            filedirectory = 'txt'
                            filepath = "/txt/"
                        elif fileType.upper() == "DOC" or fileType.upper() == "DOCX" or fileType.upper() == "XLS":
                            img = "/assets/images/pic/doc.jpg"
                            filedirectory = 'txt'
                            filepath = "/txt/"
                        else:
                            filepath = "/video/"
                            filedirectory = 'video'
                            img = "/assets/images/pic/flv.jpg"
                        path = os.path.join(eeacl.settings.FILE_UPLOAD_TEMP_DIR, filedirectory)
                        file_name = 'v_' + str(uuid.uuid1()) + '.' + fileType
                        path_file = os.path.join(path, file_name)
                        parser = open(path_file, 'wb+')
                        for chunk in file.chunks():
                            parser.write(chunk)
                        parser.close()

                        case = Case.objects.get(pk=caseId)
                        video = Video(case=case, name=filename, img=img, link=(filepath + file_name),
                                      type=fileType.upper(), filesize=filesize)
                        video.save()

                        f['name'] = file_name
                        f['size'] = 1
                        return HttpResponse(simplejson.dumps(f))
                    else:
                        HttpResponse(_("only 'MP4', 'FLV', 'PDF', 'DOC', 'DOCX', 'XLS'"))
        except:
            f['error'] = _("Request parameters error")
            return HttpResponse(simplejson.dumps(f))
    raise Http404


def profile_upload(file):
    '''图片上传函数'''
    if file:
        path = os.path.join(eeacl.settings.FILE_UPLOAD_TEMP_DIR, 'upload')
        fileType = str(file.name).split('.')[-1]
        file_name = str(uuid.uuid1()) + file.name[file.name.rfind('.'):]
        path_file = os.path.join(path, file_name)
        parser = open(path_file, 'wb+')
        for chunk in file.chunks():
            parser.write(chunk)
        parser.close()
        try:
            #if img.mode != "RGB":
            #img = img.convert("RGB")
            #img.save(path_file, 'jpeg', quality=100)
            image = PILImage.open(path_file)
            x, y = image.size
            xsize = 500
            ysize = y * xsize / x
            image.thumbnail((xsize, ysize), PILImage.ANTIALIAS)
            s_file_name = "s_" + file_name
            s_path = os.path.join(path, s_file_name)
            image.save(s_path)
            if fileType == 'gif':
                return file_name
            else:
                return s_file_name
        except:
            return ""
    return ""


@login_required(login_url='/login/')
def addProblem(request):
    if request.method == 'POST':
        case = Case.objects.get(pk=request.POST['caseId'])
        problem_type = ProblemType.objects.get(pk=request.POST['problemType'])
        problem = Problem(name=request.POST['problemName'], case=case,
                          problem_type=problem_type,
                          description=request.POST['problemDescription'])
        problem.save()
        if request.POST['solutionName']:
            solution = Solution(name=request.POST['solutionName'], case=case,
                                problem=problem, description=request.POST['solutionDescription'])
            solution.save()
        return render(request, 'success.html', {'message': _("Case add success")})
    else:
        problemType = ProblemType.objects.all()
        return render(request, 'addProblem.html', {'problemTypes': problemType, 'caseId': request.GET['caseId']})


@login_required(login_url='/login/')
def problemList(request, id):
    case = Case.objects.get(pk=id)
    problemList = Problem.objects.filter(case=case)
    return render(request, 'problemList.html', {'problemList': problemList, 'case': case})


@login_required(login_url='/login/')
def updateProblem(request, id):
    problemTypes = ProblemType.objects.filter()
    problem = Problem.objects.get(pk=id)
    solutions = Solution.objects.filter(problem=problem)
    solution = None
    if solutions:
        solution = solutions[0]
    return render(request, 'updateProblem.html',
                  {'problem': problem, 'solution': solution, 'problemTypes': problemTypes})


@login_required(login_url='/login/')
def problemUpdate(request):
    case = Case.objects.get(pk=request.POST['caseId'])
    problem_type = ProblemType.objects.get(pk=request.POST['problemType'])
    problem_id = request.POST['problemId']
    problem = Problem(name=request.POST['problemName'], id=problem_id, case=case,
                      problem_type=problem_type, description=request.POST['problemDescription'])
    problem.save()
    solution_id = request.POST['solutionId']
    if request.POST['solutionName']:
        if solution_id:
            solution = Solution(id=solution_id, name=request.POST['solutionName'], case=problem.case,
                                problem=problem, description=request.POST['solutionDescription'])
            solution.save()
        else:
            solution = Solution(name=request.POST['solutionName'], case=problem.case,
                                problem=problem, description=request.POST['solutionDescription'])
            solution.save()
    return render(request, 'success.html', {'message': _("Case update success")})


@login_required(login_url='/login/')
def problem(request, id):
    problem = Problem.objects.get(pk=id)
    solutions = Solution.objects.filter(problem=problem)
    return render(request, 'problem.html', {'problem': problem, 'case': problem.case, 'solutions': solutions})


@login_required(login_url='/login/')
def saveAnswer(request, id):
    type = request.GET['type']
    content = request.GET['content']
    if type and content:
        if type == '1':
            answerId = request.GET['answerId']
            if answerId:
                answer = Answer.objects.get(pk=answerId)
                answer.content = content
                answer.date = datetime.datetime.now()
                answer.save()
        elif type == '2':
            questionId = request.GET['questionId']
            if questionId:
                answer = Answer(user=request.user, question=Question.objects.get(pk=questionId),
                                date=datetime.datetime.now(), content=content, case=Case.objects.get(pk=id))
                answer.save()
    return HttpResponse("")


def showUserAnswer(request, id):
    userid = request.GET['userId']
    if userid and id:
        question = Question.objects.all().order_by('sort')
        answer = Answer.objects.filter(case=id, user=User.objects.get(pk=userid)).order_by('question')
        s = []
        for q in question:
            isanswer = False
            for a in answer:
                if a.question.id == q.id:
                    s.append(a)
                    isanswer = True
                    continue
            if isanswer:
                pass
            else:
                newa = Answer(question=q, content='')
                s.append(newa)
        return render(request, 'answerInfo.html', {'s': s})


@login_required(login_url='/login/')
def setting(request):
    if request.method == 'POST':
        user = User.objects.all()
        usernameExist = user.exclude(id=request.user.id)
        emailExist = user.exclude(id=request.user.id)
        usernameExist = usernameExist.filter(username=request.POST['username'])
        emailExist = emailExist.filter(email=request.POST['email'])
        if usernameExist:
            return render(request, 'setting.html', {'message': _("Username already exists")})
        if emailExist:
            return render(request, 'setting.html', {'message': _("Email already exists")})
        currentUser = request.user
        currentUser.username = request.POST['username']
        currentUser.email = request.POST['email']
        currentUser.save()
        return render(request, 'setting.html', {'message': _("Success")})
    else:
        return render(request, 'setting.html', {})




